package com.lecloud.util;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

public class FileUploader {

	public JSONObject doUpload(String url, Map<String, String> map, File file) {

		HttpPost httpPost = new HttpPost(url);

		// 创建多实体
		MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
		// 添加map里的内容
		if (map != null) {
			for (String key : map.keySet()) {
				meBuilder.addPart(key, new StringBody(map.get(key), ContentType.TEXT_PLAIN));
			}
		}
		// 添加文件实体
		FileBody fileBody = new FileBody(file);
		meBuilder.addPart("file", fileBody);

		// 使用多实体创建请求实体
		HttpEntity reqEntity = meBuilder.build();
		httpPost.setEntity(reqEntity);

		return sendHttpPost(httpPost);
	}

	/**
	 * 发送Post请求
	 * 
	 * @param httpPost
	 * @return
	 */
	private JSONObject sendHttpPost(HttpPost httpPost) {
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		HttpEntity entity = null;
		String responseContent = null;
		try {
			// 创建默认的httpClient实例.
			httpClient = HttpClients.createDefault();
			// 执行请求
			response = httpClient.execute(httpPost);
			entity = response.getEntity();
			responseContent = EntityUtils.toString(entity, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭连接,释放资源
				if (response != null) {
					response.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return JSONObject.parseObject(responseContent);
	}

}
